import GameControler from "./GameControler.js"
import Player from "./Player.js"
import Pool from "./Pool.js"
import SilverBullet from "./SilverBullet.js"

export default class Game{
  canvas:HTMLCanvasElement
  context:CanvasRenderingContext2D
  player:Player
  timer:number = 0
  gameControl:GameControler
  playerBullets:Array<SilverBullet> = new Array<SilverBullet>()
  constructor(parent:HTMLElement){
    this.canvas = document.createElement('canvas')
    this.context = this.canvas.getContext('2d') as CanvasRenderingContext2D
    parent.appendChild(this.canvas)
    this.canvas.width = parent.clientWidth
    this.canvas.height = parent.clientHeight
    this.player = new Player(this.canvas.width / 2 - 60,this.canvas.height - 50,116,95,'./assets/a2-3.png')
    this.gameControl = new GameControler(parent)
    this.player.moveSpeed = 2.5
    this.player.setMoveArea(this.canvas.width,this.canvas.height)
    this.context && this.player.initOutBorder(this.context)
   
  }
  render(){
    // if(!this.context) return;
    
    this.context?.clearRect(0,0,this.canvas.width,this.canvas.height)

    this.playerBullets.forEach(e=>{
      return e.draw(this.context)
    })

    this.player.draw(this.context)
  }
  update(){
    this.control()
    this.playerShoot()
    this.render()
    this.timer = requestAnimationFrame(this.update.bind(this))
  }
  start(){
    this.timer = requestAnimationFrame(this.update.bind(this))
  }
  control(){
    if(!this.gameControl.isDrag) return;
    this.player.direction = this.gameControl.currentRadiuns;
    this.player.move()
  }
  playerShoot(){
    this.playerBullets.forEach((e,i)=>{
      e.move()
      if(e.y <= -200){
        this.playerBullets.splice(i,1)
        Pool.recycleBullet(e)
      }
    })
    if(this.player.shootReay){
      let b = this.player.shoot()
      this.playerBullets.push(...b)
    }
  }
}